/**
 * @author chenjian2@staff.sina.com.cn
 */
$Import('app.common.getElement');
STK.register('app.actui.tree', function($){
	return function(node,opts){
		var that	= {},dEvent,cEvt,selectedNode;
			opts = $.parseParam({
				actionType: 'item',
				parentNode: "UL",
				collapseClass: "m-collapsed",
				expandClass: "m-expanded",
				selectClass: 'm-selected'
			}, opts);
		var bindDOMFuns = {
			toggle: function(spec){
				var el	= spec.el;
				var data = spec.data;
				var menu = $.core.dom.next(el);
				if($.core.dom.isNode(menu) && menu.nodeName == opts.parentNode){
					var isOpen = false;
					if(menu.style.display !== "none"){
						isOpen = true;
					}
					menu.style.display = isOpen ? 'none' : '';
					$.removeClassName(el, isOpen ? opts.expandClass : opts.collapseClass);
					$.addClassName(el,isOpen ? opts.collapseClass : opts.expandClass);
				}else{
					
				}
			},
			select:function(spec){
				var el	= spec.el;
				var data = spec.data;
				if(selectedNode){
					$.removeClassName(selectedNode,opts.selectClass);
				}
				$.addClassName(el,opts.selectClass);
				selectedNode = el;
				$.custEvent.fire(cEvt, 'onSelect', [spec]);
			}
		};
		var delegatedEvent = {
			itemClick: function(spec){
				bindDOMFuns.select(spec);
				bindDOMFuns.toggle(spec);
			},
			itemDblClick: function(spec){
				bindDOMFuns.toggle(spec);
			}
		};
		var bindDOM = function(){
			dEvent = $.core.evt.delegatedEvent(node);
			dEvent.add(opts.actionType, 'click' , delegatedEvent.itemClick);
//			dEvent.add(opts.actionType, 'dblclick' , delegatedEvent.itemDblClick);
			
		};
		
		var argsCheck = function(){
			if (!$.core.dom.isNode(node)) {
				throw "[STK.module.tree]:node is not a Node!";
			}
		};
		var parseDOM = function(){};
		
		var bindListener = function(){
			cEvt = $.custEvent.define(node, ['onSelect']);
		};
		
		var destroy = function(){
			bindDOMFuns = null;
		};
		var init = function(){
			argsCheck();
			parseDOM();
			bindDOM();
			bindListener();
		};
		init();
		that.destroy = destroy;
		return that;

	};
});